<?php

error_reporting(E_ALL);
ini_set('display_errors', '1');

/* Include connection to DB */
include_once("../includes/config.inc.php");
include_once(MYSQL);

/* Start session if it isn't already started */
if(!isset($_SESSION))
{
  session_start();
}

if($_SERVER['REQUEST_METHOD'] == "POST")
{
  if(isset($_POST['email'], $_POST['pw1'], $_POST['pw2']))
  {
    $email = $_POST['email'];
    $pw1 = $_POST['pw1'];
    $pw2 = $_POST['pw2'];

    if($pw1 != $pw2)
    {
      if(!headers_sent())
      {
        header('Location: ../create_account.php?err=1');
      }
      else
      {
        echo "<script>window.location.replace('../create_account.php?err=1');</script>";
      }
    }

    $q = "SELECT * FROM User WHERE email='" . $email . "';";
    $r = mysqli_query($dbc, $q);
    $row = mysqli_fetch_array($r);
    
    if(isset($row))
    {
      /* Account name already taken */
      if(!headers_sent())
      {
        header('Location: ../create_account.php?err=2');
      }
      else
      {
        echo "<script>window.location.replace('../create_account.php?err=2');</script>";
      }
    }
    
    /* If the passwords are the same and there is no user with the same name,
       insert */
    if(!isset($row) && ($pw1 == $pw2))
    {
      $email = strip_tags($email);
      $pw1 = strip_tags($pw1);
      $pw2 = strip_tags($pw2);

      /* Stored Procedure insert query to counter SQL injection attempts*/
      $q = 'INSERT INTO User (email, password, date_created) VALUES (?, SHA1(?), NOW())';
      $stmt = mysqli_prepare($dbc, $q);
      mysqli_stmt_bind_param($stmt, 'ss', $email, $pw1);
      mysqli_stmt_execute($stmt);
      mysqli_stmt_close($stmt);

      /* Redirect the user to the login page so they can log in with their new account */
      if(!headers_sent())
      {
        header('Location: ../login.php?newaccount=1');
      }
      else
      {
        echo "<script>window.location.replace('../login.php?newaccount=1');</script>";
      }
    }
  }
  else
  {
    /* Error 3 means not all fields were filled out in the form */
    if(!headers_sent())
    {
      header('Location: ../create_account.php?err=3');
    }
    else
    {
      echo "<script>window.location.replace('../create_account.php?err=3');</script>";
    }
  }
}
else
{
  /* The user shouldn't be at this page unless they submitted a create_account form. */
  if(!headers_sent())
  {
    header('Location: ../create_account.php');
  }
  else
  {
    echo "<script>window.location.replace('../create_account.php');</script>";
  }
}
?>
